<?php


namespace app\zhengmaotong\controller;

use app\zhengmaotong\model\BannerModel;
use app\zhengmaotong\model\GoodsModel;
use app\zhengmaotong\validate\GoodsValidate;
use cmf\controller\AdminBaseController;

class GoodsController extends AdminBaseController
{
    //商品首页
    public function index()
    {
        $name = input('name', '');
        $where = [];
        if (!empty($name)) {
            $where[] = ['name', 'like', "%$name%"];
        }
        $goods = GoodsModel::order('create_time', 'DESC')
            ->where($where)
            ->paginate(1);
        $goods->appends(request()->param());
        return $this->fetch('index', [
            'Goods' => $goods
        ]);
    }

    //添加页面
    public function add()
    {
        return $this->fetch();
    }

    //添加功能
    public function addPost()
    {

        $data = input('post.');
        $validate = new GoodsValidate();
        //验证器
        $res = $validate->scene('add')->check($data);
        if (!$res) {
            $this->error($validate->getError());
        }
        $data['create_time'] = date('Y-m-d H:i:s');
        $banner = GoodsModel::create($data);
        if ($banner) {
            $this->success('添加成功');
        } else {
            $this->error('添加失败');
        }
    }

    //修改页面
    public function edit()
    {

        $id = input('id');
        if (!$id) {
            $this->error('错误');
        }
        $goods = GoodsModel::find($id);
        if (!$goods) {
            $this->error('错误');
        }
        return $this->fetch('edit', [
            'Goods' => $goods
        ]);
    }

    //修改功能
    public function editPost()
    {
        $data = input('post.');
        if (!$data['id']) {
            $this->error('ID错误');
        }
        $validate = new GoodsValidate();
        //验证器
        $res = $validate->scene('edit')->check($data);
        if (!$res) {
            $this->error($validate->getError());
        }
        $Goods = GoodsModel::find($data['id']);
        if (!$Goods) {
            $this->error('错误');
        }
        $Goods->images = $data['images'];
        $Goods->name = $data['name'];
        $Goods->url = $data['url'];
        $Goods->status = $data['status'];

        if ($Goods->save()) {
            $this->success('保存成功', 'Goods/index');
        } else {
            $this->error('保存失败');
        }
    }

    //删除功能
    public function del()
    {
        $id = input('id');
        if (!$id) {
            $this->error('错误');
        }
        $Goods = GoodsModel::find($id);
        if ($Goods->delete()) {
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }

    public function px()
    {
        $model = new GoodsModel;
        parent::listOrders($model);
        $this->success('排序成功');
    }
}